Titanium.include('globals.js');


exports.createSettings = function() {
	if(Ti.Platform.osname == 'iphone' )
	  {
	    Ti.App.Properties.setString('osname', 'iphone');
		Ti.App.Properties.setString('fontsizeDefault', 14);
		Ti.App.Properties.setString('fontsizeDialog', 18);
		Ti.App.Properties.setString('fontsizeLarge', 16);
	
	  }
	  else
	  {
	  	Ti.App.Properties.setString('osname', 'noniphone');
		Ti.App.Properties.setString('fontsizeDefault', 16);
		Ti.App.Properties.setString('fontsizeDialog', 18);
		Ti.App.Properties.setString('fontsizeLarge', 20);
	  }	
	
	
	Ti.App.Properties.setInt('isLogin',0);
	Ti.App.Properties.setInt('IsBuyProgram', 0);
	Ti.App.Properties.setInt('IsActiveDownload', 0);
	Ti.App.Properties.setInt('IsBuyLectureID', 0);
	Ti.App.Properties.setInt('LectureID', 0);
	Ti.App.Properties.setInt('login_username_id', 0);
	
	
	////////////LOGIN IF//////////// 
	//getLoginUser( Ti.App.Properties.getString('login_email'),Ti.App.Properties.getString('login_password'))
	
	
};



getLoginUser = function(Email,Password) {
	
	var param = {   
	  "UserName_Email" : Email,
	  "Password" : Password
	};
	try {  	
	   	   var xhr = Titanium.Network.createHTTPClient({
		   onload : function(e) 
		   {
		         Titanium.API.info(this.responseText);
				 json = this.responseText;
				 json=json.replace('<string xmlns="http://tempuri.org/">', '');
				 json=json.replace('<?xml version="1.0" encoding="utf-8"?>', '');
				 json=json.replace('</string>', '');
				 //alert(FullName+','+Sex+','+Birthday+','+Address+','+Email+','+UserName+','+Password+','+Postdate)
				 //alert(json)
			
				 response = JSON.parse(json);
			     //alert(response.OBJECT.length);
			     if(response.OBJECT.length>=1)
			     {
			     	//require('settings').createAlertDialog(Globals.title,Globals.loginsuccesfull);
			     	Ti.App.Properties.setInt('isLogin', 1);
			     	Ti.App.Properties.setInt('login_username_id', response.OBJECT[0].Id);
			     	Ti.App.Properties.setString('login_username_email', response.OBJECT[0].Email);
			     	Ti.App.Properties.setString('login_username', response.OBJECT[0].UserName);
			     	Ti.App.Properties.setString('login_email', response.OBJECT[0].Email);
					Ti.App.Properties.setString('login_password', response.OBJECT[0].PasswordNoEncode);
				
					Ti.App.Properties.setString('login_FullName', response.OBJECT[0].FullName);
					Ti.App.Properties.setString('login_Address', response.OBJECT[0].Address);
					Ti.App.Properties.setString('login_Sex', response.OBJECT[0].Sex);
					Ti.App.Properties.setString('login_Birthday', response.OBJECT[0].Birthday);
					Ti.App.Properties.setString('login_Card', response.OBJECT[0].cr_value_card);
					
					
					Ti.App.Properties.setInt('IsBuyProgram', response.OBJECT[0].IsBuyProgram);
					Ti.App.Properties.setInt('IsActiveDownload', response.OBJECT[0].IsActiveDownload);
			     }
			     else
			     {
			     	Ti.App.Properties.setInt('isLogin',0);
			     	
			     }
			    
				
		   }, 
		   onerror : function(e) {
		   	 Ti.App.Properties.setInt('isLogin',0);
		   },
		   timeout : 5000
    
		});
		xhr.open("POST",Globals.serviceurl_UserLogin);
		xhr.send(param);
	 	} catch (e) {
	 			Ti.App.Properties.setInt('isLogin',0);
	            Ti.API.info(e);
	    }
	
	};






exports.createAlertConnectError = function()
{
	var confirm = Titanium.UI.createAlertDialog({ 
					            title: Globals.title1, 
					            message:Globals.connecterror, 
					            buttonNames: [Globals.btOk]
					    });
	confirm.show();   
}
exports.createAlertDialog= function(title,message)
{
	var confirm = Titanium.UI.createAlertDialog({ 
					            title: title, 
					            message:message, 
					            buttonNames: [Globals.btOk]
					    });
	confirm.show();   
}



exports.checkemail= function(emailAddress)
	{
		var testresults;
		var str = emailAddress;
		var filter = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
		if (filter.test(str))
		{
			testresults = true;
		}
		else
		{
			testresults = false;
		}
		return (testresults);
	};

/////////////////////////////CREATE CONTROL SEGMENT///////////////////////////////////////////////////////////
var DEFAULTS = {
	labels: ['One', 'Two'],
	index: 0,
	backgroundColor: '#ccc',
	backgroundSelectedColor: 'blue',
	borderColor: '#444',
	borderWidth: 1,
	height: 'auto',
	androidHeight: '40dp',
	width: '90%',
	color: '#000',
	fontWeight: 'bold',
	fontSize: 18
};
var osname = Ti.Platform.osname;
exports.makeTabbedBar = function(/*map*/_params, /*function*/ _fn){
    if (osname != 'android') {
        // if iOS, just return the native tabbed bar
       // var tb1 = Titanium.UI.iOS.createTabbedBar(mixin(DEFAULTS, _params));
        
        var tb1 = Titanium.UI.createTabbedBar({
		    labels:['One', 'Two', 'Three'],
		    backgroundColor:'#336699',
		    top: 20,//topfirst+ (heighttext*3)+15,
		    style:Titanium.UI.iPhone.SystemButtonStyle.BAR,
		    height: 50,//heighttext,
		    width:200,
		    index:_params.index
		});
        
        
        if(_fn) {
	        tb1.addEventListener('click', function(e){
	            _fn(e.source.index);
	        });
        }
        return tb1;
        
    } else {
		// build pseudo tabbed bar for Android
        var wrapper = Ti.UI.createView({
			width:(_params.width) ? _params.width : DEFAULTS.width,
			height: (_params.height) ? _params.height : DEFAULTS.androidHeight,
			top: (_params.top) ? _params.top : DEFAULTS.top,
			left: (_params.left) ? _params.left : DEFAULTS.left
		
		});
		var numButtons = (_params.labels.length) ? _params.labels.length : DEFAULTS.labels.length;
		// need to calculate width of sub-buttons, but view.width could have been set as a string
		var tmpWidth = (_params.width) ? _params.width : DEFAULTS.width;
		var subBtnWidth = 0;
		if(typeof(tmpWidth)=='number') {
			subBtnWidth = Math.round(tmpWidth/numButtons);
		} else if(typeof(tmpWidth)=='string' && !isNaN(parseInt(tmpWidth))) {
			// looks like we've got a percentage width
			subBtnWidth = Math.round((parseInt(tmpWidth)/100 * Ti.Platform.displayCaps.platformWidth)/numButtons);
		} else {
			// looks like 'auto' was used
			subBtnWidth = Math.round((0.9 * Ti.Platform.displayCaps.platformWidth)/numButtons);
		}
		
		var btnArray = [];
		for(var i=0; i<numButtons; i++) {
			// create the sub-buttons
			var subBtn = Ti.UI.createView({
				backgroundColor: (_params.backgroundColor) ? _params.backgroundColor : DEFAULTS.backgroundColor,
				borderColor: (_params.borderColor) ? _params.borderColor : DEFAULTS.borderColor,
				borderWidth: (_params.borderWidth) ? _params.borderWidth : DEFAULTS.borderWidth,
				left: (i * subBtnWidth),
				width: subBtnWidth,
				height: (_params.height) ? _params.height : DEFAULTS.androidHeight,
				myIndex: i
			});
			subBtn.add(Ti.UI.createLabel({
				text: _params.labels[i],
				color: (_params.color) ? _params.color : DEFAULTS.color,
				font: {
					fontWeight: (_params.fontWeight) ? _params.fontWeight : DEFAULTS.fontWeight,
					fontSize: (_params.fontSize) ? _params.fontSize : DEFAULTS.fontSize
				}
			}));
			if(_params.androidBackgroundImage) {
				subBtn.backgroundImage = _params.androidBackgroundImage;
			}
			if(i==0) {
				subBtn.backgroundColor = (_params.backgroundSelectedColor) ? _params.backgroundSelectedColor : DEFAULTS.backgroundSelectedColor;
				if(_params.androidBackgroundSelectedImage) {
					subBtn.backgroundImage = _params.androidBackgroundSelectedImage;
				}
			}
			
			btnArray.push(subBtn);
			wrapper.add(subBtn);
		}
        wrapper.addEventListener('click', function(e){
			for(var i=0; i<numButtons; i++) {
				btnArray[i].backgroundColor = (_params.backgroundColor) ? _params.backgroundColor : DEFAULTS.backgroundColor;
				if(_params.androidBackgroundImage) {
					btnArray[i].backgroundImage = _params.androidBackgroundImage;
				}
			}
			if(e.source.myIndex) {
				e.source.backgroundColor =  (_params.backgroundSelectedColor) ? _params.backgroundSelectedColor : DEFAULTS.backgroundSelectedColor;
				if(_params.androidBackgroundSelectedImage) {
					e.source.backgroundImage = _params.androidBackgroundSelectedImage;
				}
			} else {
				e.source.parent.backgroundColor =  (_params.backgroundSelectedColor) ? _params.backgroundSelectedColor : DEFAULTS.backgroundSelectedColor;
				if(_params.androidBackgroundSelectedImage) {
					e.source.parent.backgroundImage = _params.androidBackgroundSelectedImage;
				}
			}
			
	        if(_fn) {
	            _fn((e.source.myIndex) ? e.source.myIndex : e.source.parent.myIndex);
	        }
        });
		return wrapper;
	}
}; // end makeTabbedBar


exports.loadJson= function(Jsonurl,param)
{
	  alert('json')

	var param = {        
	  "UserId" : 543769,
	  "LectureId" : 635,
	  "Price" : 2000
    };

	var xhr = Titanium.Network.createHTTPClient({
		   onload : function(e) 
		   {
		       Titanium.API.info(this.responseText);
			   json = this.responseText;
			   json=json.replace('<string xmlns="http://tempuri.org/">', '');
			   json=json.replace('<?xml version="1.0" encoding="utf-8"?>', '');
			   json=json.replace('</string>', '');
			   //alert(json)
			   return json;
			
			   //response = JSON.parse(json);
			   //alert(response.OBJECT.length);
			   //Codestrong.ui.activityIndicator.hideModal();
		   },
		   onerror : function(e) {
		      // Codestrong.ui.activityIndicator.hideModal();
		   },
		   timeout : 5000
    
	});
	xhr.open("POST",Globals.Jsonurl);
	xhr.send(param);
	return response;
};

exports.GetJson= function(Jsonurl,param,onload_even,error_even)
{
	//Codestrong.ui.activityIndicator.showModal(Globals.loading, Globals.timeout, Globals.loadingTimeout);
	var xhr = Titanium.Network.createHTTPClient({
		   onload : function(e) 
		   {
		       Titanium.API.info(this.responseText);
			   json = this.responseText;
			   json=json.replace('<string xmlns="http://tempuri.org/">', '');
			   json=json.replace('<?xml version="1.0" encoding="utf-8"?>', '');
			   json=json.replace('</string>', '');
			   json=json.replace(/(\r\n|\n|\r)/gm,"");
			   response = JSON.parse(json).OBJECT;
			   //if(response.length>0)
			   		Ti.App.fireEvent(onload_even,{datajson:response}); 
			   //Codestrong.ui.activityIndicator.hideModal();
		   },
		   onerror : function(e) {
		      Ti.App.fireEvent(error_even,{datajson:response}); 
		   },
		   timeout : 5000
    
	});
	xhr.open("POST",Jsonurl);
	xhr.send(param);
	
};
exports.GetJsonFunction= function(Jsonurl,param,onload_function,error_function)
{
	//Codestrong.ui.activityIndicator.showModal(Globals.loading, Globals.timeout, Globals.loadingTimeout);
	var xhr = Titanium.Network.createHTTPClient({
		
		   onload : function(e) 
		   {
		      // Titanium.API.info(this.responseText);
			   json = this.responseText;
			   json=json.replace('<string xmlns="http://tempuri.org/">', '');
			   json=json.replace('<?xml version="1.0" encoding="utf-8"?>', '');
			   json=json.replace('</string>', '');
			   json=json.replace(/(\r\n|\n|\r)/gm,"");
			   response = JSON.parse(json).OBJECT;
			  // Titanium.API.info(response);
			   //onload_function(this.responseText);
			   
			    onload_function({
					datajson :response,
				});
				
			   //Codestrong.ui.activityIndicator.hideModal();
		   },
		   onerror : function(e) {
		       error_function({
				  datajson:response
			   });
		   },
		   timeout : 5000
    
	});
	xhr.open("POST",Jsonurl);
	xhr.send(param);
	
};


exports.downloadMultiFile = function(downloadQueue,updatevalueprocess ,callBack_DownloadOneFileFinished, callBack_DownloadMultipleFileFinished) {

	var queueIndex = 0;

	var processQueue = function(download_result) {
		//once the download of one file is finished the downloadOneFile will call back the processQueue
		//which will move the index forward and download another file
			
		if( typeof (download_result) !== 'undefined') {
			callBack_DownloadOneFileFinished(download_result);
		}
		if(queueIndex < downloadQueue.length) {


			exports.downloadOneFile(downloadQueue[queueIndex], downloadQueue[queueIndex].filepath, processQueue,updatevalueprocess);
			queueIndex++;

		} else {
			callBack_DownloadMultipleFileFinished();
		}

	};
	processQueue();
};

exports.downloadOneFile = function(downloadQueue, localFilepath, callBack_DownloadOneFileFinished,updatevalueprocess) {

	var c = Titanium.Network.createHTTPClient();
	if(null != callBack_DownloadOneFileFinished) {
		c.onerror = function(e) {
			Ti.API.info('MyApp: Download failed: url= ' + url + ' Error=' + e.error);

			callBack_DownloadOneFileFinished({
				status : e.error,
				path : '',
				index:downloadQueue.index,
				length:downloadQueue.length
			});
		};
		c.ondatastream = function(e)
		{
			//Ti.API.info('value :' + e.progress);
			updatevalueprocess({
				value : e.progress,
				VideoName:downloadQueue.item.VideoName,
				index:downloadQueue.index,
				length:downloadQueue.length
			});
					
			
		};
		c.onload = function(e) {

			if(Titanium.Platform.name === 'android') {
				// On android HTTPClient will not save the file to disk. So have to hack around it
				Ti.API.info('MyApp: (Andoid) Downloaded this file from server:.' + localFilepath);
				var f = Titanium.Filesystem.getFile(localFilepath);
				f.write(c.responseData);
			}

			callBack_DownloadOneFileFinished({
				status : c.status,
				path : localFilepath,
				item : downloadQueue.item,
				index:downloadQueue.index,
				length:downloadQueue.length
			});
		};
	}

	c.open('GET', downloadQueue.url);

	if(null != localFilepath && Titanium.Platform.name !== 'android') {
		Ti.API.info('MyApp:  (iOS) Downloaded this file from server:.' + localFilepath);
		c.file = Titanium.Filesystem.getFile(localFilepath);
	}

	c.send();
};